package com.techbrand.lb7.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.RequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.techbrand.lb7.dao.CustomerDao;
import com.techbrand.lb7.domain.Address;
import com.techbrand.lb7.domain.Customer;
import com.techbrand.lb7.domain.Person;

public class CustomerFormController extends SimpleFormController {

	private CustomerDao customerDao;

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		long custId = RequestUtils.getLongParameter(request, "custId", 0);
		Customer form = new Customer();
		if (custId != 0) {
			Customer cust = customerDao.getById(custId);
			form.setCustomerId(cust.getCustomerId());
			form.setCustomerName(cust.getCustomerName());
			form.setContactPerson(cust.getContactPerson());
			form.setPhone(cust.getPhone());
			form.setMobile(cust.getMobile());
			form.setResidentAddress(cust.getResidentAddress());
		} else {
			form.setContactPerson(new Person());
			form.setResidentAddress(new Address());
		}
		return form;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Customer form = (Customer) command;
		customerDao.save(form);
		
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("customer", form);

		return new ModelAndView(getSuccessView(), model);
	}

	public CustomerDao getCustomerDao() {
		return customerDao;
	}

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}
}
